package saxion.sensorframework;

import java.io.File;
import java.util.Properties;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.log4j.Logger;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * Validates data
 * @author Erik & Martijn
 *
 */
public class SensorValidator {

	static Logger logger = Logger.getLogger(SensorValidator.class.getName()); /**< logger  \sa SensorFramework::logger */
	private Properties properties; /**< Properties file. \sa SensorFramework::properties*/
	
	private String xsdSensorLocation; /**< location of sensor xsd*/
	

	/**
	 * \brief Validate Senorvalues
	 * 
	 * @param properties \sa SensorFramework::properties
	 */
	public SensorValidator(Properties properties)
	{
		this.properties = properties;
		initialize();
	}
	
	/**
	 * \brief initialize variables
	 *  
	 *  set XSD location for sensor
	 */
	private void initialize()
	{
		 xsdSensorLocation = properties.getProperty("xsdSensorLocation");
	}
	
	/**
	 * \brief Validate xml with sensor data
	 * 
	 * Validate given xml document by comparing it to the xsd for a senor xml document. 
	 * 
	 * @param xml
	 * @return true if no error false with errors
	 */
	public boolean validateSensorXML(String xml)
	{
		   Source source = new StreamSource(xml);
		   
	        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
	        Schema schema = null;
			try {
				schema = sf.newSchema(new File(xsdSensorLocation));
			} catch (SAXException e) {
				logger.error("\n unable to validate file ");
				e.printStackTrace();
				return false;
			} 
	 
	        Validator validator = schema.newValidator();
	        validator.setErrorHandler(new ValidatorErrorHandler());
	        try {
				validator.validate(source);
			} catch (Exception e) {
				logger.error("\n unable to validate file ");
				e.printStackTrace();
				return false;
			}
	        
	        return true;
	}
	
	/**
	 * Error handler for comparing xsd to xml document.
	 * 
	 * @author Erik & Martijn
	 *
	 */
	public class ValidatorErrorHandler implements ErrorHandler {

	    public void warning(SAXParseException exception) throws SAXException {
	    	logger.warn("\nWARNING");
	        exception.printStackTrace();
	    }
	 
	    public void error(SAXParseException exception) throws SAXException {
	    	logger.error("\nERROR");
	        exception.printStackTrace();
	    }
	 
	    public void fatalError(SAXParseException exception) throws SAXException {
	    	logger.error("\nFATAL ERROR");
	        exception.printStackTrace();
	    } 
	}
	
}


